<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="员工姓名" prop="realName">
        <el-input
          v-model="queryParams.realName"
          placeholder="请输入员工姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select
          v-model="queryParams.gender"
          placeholder="请选择性别"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="员工类型" prop="employeeType">
        <el-select
          v-model="queryParams.employeeType"
          placeholder="请选择员工类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.OA_EMPLOYEE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="员工状态" prop="employeeStatus">
        <el-select
          v-model="queryParams.employeeStatus"
          placeholder="请选择员工状态"
          clearable
          class="!w-240px"
        >
          <el-option label="在职" :value="0" />
          <el-option label="离职" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['oa:employee-archive:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['oa:employee-archive:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
<!--      <el-table-column label="序号" align="center" prop="id" />-->
      <el-table-column label="员工编号" align="center" prop="userCode" />
      <el-table-column label="员工姓名" align="center" prop="realName" />
      <el-table-column label="联系电话" align="center" prop="phone" />
      <el-table-column label="身份证号码" align="center" prop="idCard" />
      <el-table-column label="所在部门" align="center" prop="deptName" />
      <!-- <el-table-column label="性别" align="center" prop="gender">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SYSTEM_USER_SEX" :value="scope.row.gender" />
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="入职日期" align="center" prop="hireDate" /> -->
      <!-- <el-table-column label="政治面貌" align="center" prop="politicalStatus" /> -->
      <!-- <el-table-column label="民族" align="center" prop="ethnicGroup" /> -->
<!--      <el-table-column label="户口性质" align="center" prop="householdType">-->
<!--        <template #default="scope">-->
<!--          <dict-tag :type="DICT_TYPE.OA_HOUSEHOLD_TYPE" :value="scope.row.householdType" />-->
<!--        </template>-->
<!--      </el-table-column>-->
      
      <!-- <el-table-column label="婚姻状况" align="center" prop="maritalStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.OA_MARITAL_STATUS" :value="scope.row.maritalStatus" />
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="籍贯" align="center" prop="nativePlace" /> -->
      <!-- <el-table-column label="户口所在地" align="center" prop="householdLocation" /> -->
      <!-- <el-table-column label="毕业院校" align="center" prop="graduateInstitution" /> -->
      <!-- <el-table-column label="最高学历" align="center" prop="highestDegree" /> -->
      <!-- <el-table-column label="专业" align="center" prop="major" /> -->
      <!-- <el-table-column label="毕业日期" align="center" prop="graduationDate" /> -->
      <!-- <el-table-column label="家庭住址" align="center" prop="homeAddress" /> -->
      <!-- <el-table-column label="现住地址" align="center" prop="currentAddress" /> -->
      <!-- <el-table-column label="紧急联系人手机号码" align="center" prop="emergencyContactPhone" /> -->
      <!-- <el-table-column label="紧急联系人" align="center" prop="emergencyContact" /> -->
      <!-- <el-table-column label="员工类型" align="center" prop="employeeType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.OA_EMPLOYEE_TYPE" :value="scope.row.employeeType" />
        </template>
      </el-table-column>-->
      <el-table-column label="入职日期" align="center" prop="hireDate" :formatter="dateFormatter2" />
      <el-table-column label="离职日期" align="center" prop="endDate" :formatter="dateFormatter2" />
      <el-table-column label="员工状态" align="center" prop="employeeStatus" min-width="80">
        <template #default="scope">
          <el-tag :type="scope.row.employeeStatus === 0 ? 'success' : 'info'">
            {{ scope.row.employeeStatus === 0 ? '在职' : '离职' }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- <el-table-column label="入职年限" align="center">
        <template #default="scope">
          <span>{{ calculateWorkYears(scope.row.hireDate) }}</span>
        </template>
      </el-table-column>  -->

      <!-- <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180px"
        :formatter="dateFormatter"
      /> -->
      <el-table-column label="操作" align="center" min-width="180px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('detail', scope.row.id)"
            v-hasPermi="['oa:employee-archive:query']"
          >
            查看
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['oa:employee-archive:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="warning"
            @click="handleResign(scope.row)"
            v-if="scope.row.employeeStatus === 0"
            v-hasPermi="['oa:employee-archive:update']"
          >
            离职
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['oa:employee-archive:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <EmployeeArchiveForm ref="formRef" @success="getList" />

  <!-- 离职对话框 -->
  <el-dialog v-model="resignDialogVisible" title="员工离职" width="400px">
    <el-form ref="resignFormRef" :model="resignForm" :rules="resignRules" label-width="100px">
      <el-form-item label="员工姓名">
        <el-input v-model="resignForm.realName" disabled />
      </el-form-item>
      <el-form-item label="离职日期" prop="endDate">
        <el-date-picker
          v-model="resignForm.endDate"
          type="date"
          placeholder="选择离职日期"
          value-format="YYYY-MM-DD"
          class="!w-full"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="resignDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitResign" :loading="resignLoading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter,dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { EmployeeArchiveApi, EmployeeArchiveVO } from '@/api/oa/employeearchive'
import EmployeeArchiveForm from './EmployeeArchiveForm.vue'


/** 员工档案 列表 */
defineOptions({ name: 'EmployeeArchive' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<EmployeeArchiveVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  userId: undefined,
  gender: undefined,
  employeeType: undefined,
  employeeStatus: undefined,
  realName: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// 离职相关变量
const resignDialogVisible = ref(false)
const resignLoading = ref(false)
const resignFormRef = ref()
const resignForm = reactive({
  id: undefined,
  realName: '',
  endDate: ''
})
const resignRules = {
  endDate: [{ required: true, message: '请选择离职日期', trigger: 'change' }]
}

/** 计算入职年限 */
const calculateWorkYears = (hireDate: any) => {
  console.log('计算入职年限，输入值:', hireDate, '类型:', typeof hireDate)

  if (!hireDate) {
    return ''
  }

  try {
    // 处理不同的时间格式
    let hireDateObj: Date
    const hireDateValue = hireDate

    if (typeof hireDateValue === 'string') {
      // 如果是字符串格式，直接创建Date对象
      hireDateObj = new Date(hireDateValue)
    } else if (typeof hireDateValue === 'number') {
      // 如果是数字格式（时间戳），创建Date对象
      hireDateObj = new Date(hireDateValue)
    } else {
      // 如果已经是Date对象
      hireDateObj = hireDateValue
    }

    console.log('转换后的日期对象:', hireDateObj)

    // 检查日期是否有效
    if (isNaN(hireDateObj.getTime())) {
      console.log('日期无效，返回空字符串')
      return ''
    }

    const currentDate = new Date()
    const diffTime = Math.abs(currentDate.getTime() - hireDateObj.getTime())
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    const years = (diffDays / 365).toFixed(1)

    const result = `${years} 年`
    console.log('计算结果:', result)
    return result
  } catch (error) {
    console.error('计算入职年限时出错:', error)
    return ''
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await EmployeeArchiveApi.getEmployeeArchivePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await EmployeeArchiveApi.deleteEmployeeArchive(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await EmployeeArchiveApi.exportEmployeeArchive(queryParams)
    download.excel(data, '员工档案.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 离职按钮操作 */
const handleResign = (row: any) => {
  resignForm.id = row.id
  resignForm.realName = row.realName
  resignForm.endDate = ''
  resignDialogVisible.value = true
}

/** 提交离职 */
const submitResign = async () => {
  if (!resignFormRef.value) return
  await resignFormRef.value.validate()

  try {
    resignLoading.value = true
    await EmployeeArchiveApi.resignEmployee(resignForm.id, resignForm.endDate)
    message.success('离职操作成功')
    resignDialogVisible.value = false
    await getList()
  } catch {
  } finally {
    resignLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})

</script>
